package com.qike.yuandongguoji.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.gson.Gson;
import com.qike.yuandongguoji.controller.NewUseCarListVo;
import com.qike.yuandongguoji.dto.*;
import com.qike.yuandongguoji.enums.LeaveingOrderStatusEnums;
import com.qike.yuandongguoji.enums.OrderTypeEnums;
import com.qike.yuandongguoji.enums.StatusEnums;
import com.qike.yuandongguoji.mapper.*;
import com.qike.yuandongguoji.pojo.*;
import com.qike.yuandongguoji.service.PcService;
import com.qike.yuandongguoji.service.TokenService;
import com.qike.yuandongguoji.service.WeChatService;
import com.qike.yuandongguoji.tools.TimeTool;
import com.qike.yuandongguoji.vo.*;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author: Eric.zhou
 * @Date: 2020/8/5 10:44
 */
@Service
public class PcServiceImpl implements PcService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private LeavingMapper leavingMapper;
    @Autowired
    private OutReportMapper outReportMapper;
    @Autowired
    private UseCarMapper useCarMapper;
    @Autowired
    private MeetingRoomMapper meetingRoomMapper;
    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private CarMapper carMapper;
    @Autowired
    private WeChatService weChatService;
    @Autowired
    private NewsMapper newsMapper;


    /**
     * 登录
     *
     * @param pcLoginDto
     * @return
     */
    @Override
    public PCLoginVo login(PcLoginDto pcLoginDto) throws Exception {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(pcLoginDto.getPhone()).andPwdEqualTo(pcLoginDto.getPwd()).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        if (users.size() <= 0) {
            throw new Exception("账号密码错误");
        }
        User user = users.get(0);
        PCLoginVo vo = new PCLoginVo();
        vo.setPhone(user.getPhone());
        vo.setUid(user.getId());
        vo.setUserName(user.getName());
        vo.setToken(tokenService.getToken(user));
        return vo;
    }

    /**
     * 请假列表统计
     *
     * @param loginDto
     * @return
     */
    @Override
    public LeaveListVo leaveList(LeaveListDto loginDto) {
        LeavingExample example = new LeavingExample();
        LeavingExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(loginDto.getName())) {
            criteria.andUserNameEqualTo(loginDto.getName());
        }
        if (loginDto.getStartTime() != null && loginDto.getEndTime() != null) {
            criteria.andStartTimeGreaterThanOrEqualTo(new Date(loginDto.getStartTime())).andEndTimeLessThanOrEqualTo(new Date(loginDto.getEndTime()));
        }
        if (loginDto.getType() != null) {
            criteria.andTypeEqualTo(loginDto.getType());
        }
        criteria.andStatusEqualTo(1);
        LeaveListVo vo = new LeaveListVo();
        List<LeaveVo> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(loginDto.getStartPage(), loginDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<Leaving> leavings = leavingMapper.selectByExample(example);
        for (Leaving leaving : leavings) {
            LeaveVo leaveVo = new LeaveVo();
            leaveVo.setId(leaving.getId());
            leaveVo.setName(leaving.getUserName());
            leaveVo.setRemark(leaving.getRemark());
            leaveVo.setStatus(leaving.getStatus());
            leaveVo.setTypeName(LeaveingOrderStatusEnums.statOf(leaving.getType()).getEmsg());
            leaveVo.setType(leaving.getType());
            leaveVo.setRemark(leaving.getRemark());
            leaveVo.setStartTime(TimeTool.dateFormatNoSS(leaving.getStartTime()));
            leaveVo.setEndTime(TimeTool.dateFormatNoSS(leaving.getEndTime()));
            voList.add(leaveVo);
        }
        vo.setTotal(page.getTotal());
        vo.setVos(voList);
        return vo;
    }

    /**
     * 批量请假修改状态
     *
     * @param leaveChangeStatusDto
     */
    @Override
    public void leaveChangeStatus(LeaveChangeStatusDto leaveChangeStatusDto) throws Exception {
        if (leaveChangeStatusDto.getIds().size() <= 0) {
            throw new Exception("数量不能为0");
        }
        LeavingExample example = new LeavingExample();
        example.createCriteria().andIdIn(leaveChangeStatusDto.getIds());
        List<Leaving> leavings = leavingMapper.selectByExample(example);
        if (leavings.size() <= 0) {
            throw new Exception("数据异常");
        }
        for (Leaving leaving : leavings) {
            leaving.setStatus(leaveChangeStatusDto.getStatus());
            leavingMapper.updateByPrimaryKeySelective(leaving);
        }

    }

    /**
     * 差旅列表
     *
     * @param outListDto
     * @return
     */
    @Override
    public OutListVo outList(OutListDto outListDto) {
        OutReportExample example = new OutReportExample();
        OutReportExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(outListDto.getName())) {
            criteria.andUserNameEqualTo(outListDto.getName());
        }
        if (outListDto.getStartTime() != null && outListDto.getEndTime() != null) {
            criteria.andOutTimeStartGreaterThanOrEqualTo(new Date(outListDto.getStartTime())).andOutTimeEndLessThanOrEqualTo(new Date(outListDto.getEndTime()));
        }
        if (outListDto.getStatus() != null) {
            criteria.andOrderStatusEqualTo(outListDto.getStatus());
        }
        OutListVo vo = new OutListVo();
        List<OutVo> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(outListDto.getStartPage(), outListDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<OutReport> outReports = outReportMapper.selectByExample(example);
        for (OutReport leaving : outReports) {
            OutVo outVo = new OutVo();
            outVo.setId(leaving.getId());
            outVo.setName(leaving.getUserName());
            outVo.setRemark(leaving.getRemark());
            outVo.setStatus(leaving.getOrderStatus());
            outVo.setStartTime(TimeTool.dateFormatNoTime(leaving.getOutTimeStart()));
            outVo.setEndTime(TimeTool.dateFormatNoTime(leaving.getOutTimeEnd()));
            outVo.setAddress(leaving.getAddress());
            outVo.setAddTime(TimeTool.dateFormatNoTime(leaving.getAddTime()));
            voList.add(outVo);
        }
        vo.setTotal(page.getTotal());
        vo.setVos(voList);
        return vo;
    }

    /**
     * 差旅行程详情
     *
     * @param id
     * @return
     */
    @Override
    public OutInfoVo outInfo(Integer id) throws Exception {
        OutReport outReport = outReportMapper.selectByPrimaryKey(id);
        if (outReport == null) {
            throw new Exception("数据异常");
        }
        OutInfoVo vo = new OutInfoVo();
        vo.setAddress(outReport.getAddress());
        vo.setEndTime(TimeTool.dateFormatNoTime(outReport.getOutTimeEnd()));
        vo.setStartTime(TimeTool.dateFormatNoTime(outReport.getOutTimeStart()));
        vo.setRemark(outReport.getRemark());
        vo.setPhoto(outReport.getPhoto());
        vo.setCarId(outReport.getCarId());
        vo.setJoins(outReport.getJoinIds());
        return vo;
    }

    /**
     * 差旅行程批量修改状态
     *
     * @param leaveChangeStatusDto
     */
    @Override
    public void outChangeStatus(LeaveChangeStatusDto leaveChangeStatusDto) throws Exception {
        if (leaveChangeStatusDto.getIds().size() <= 0) {
            throw new Exception("数量不能为0");
        }
        OutReportExample example = new OutReportExample();
        example.createCriteria().andIdIn(leaveChangeStatusDto.getIds());
        List<OutReport> leavings = outReportMapper.selectByExample(example);
        if (leavings.size() <= 0) {
            throw new Exception("数据异常");
        }
        for (OutReport leaving : leavings) {
            leaving.setOrderStatus(leaveChangeStatusDto.getStatus());
            outReportMapper.updateByPrimaryKeySelective(leaving);
        }

    }

    /**
     * 用车申请列表
     *
     * @param useCarListDto
     * @return
     */
    @Override
    public UserCarVo useCarList(UseCarListDto useCarListDto) {

        UseCarExample example = new UseCarExample();
        UseCarExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(useCarListDto.getName())) {
            criteria.andUserNameEqualTo(useCarListDto.getName());
        }
        if (useCarListDto.getStartTime() != null && useCarListDto.getEndTime() != null) {
            criteria.andStartTimeLessThanOrEqualTo(new Date(useCarListDto.getStartTime())).andEndTimeGreaterThanOrEqualTo(new Date(useCarListDto.getEndTime()));
        }
        if (useCarListDto.getStatus() != null) {
            criteria.andStatusEqualTo(useCarListDto.getStatus());
        }
        if (useCarListDto.getCarId() != null) {
            criteria.andCarIdEqualTo(useCarListDto.getCarId());
        }
        UserCarVo vo = new UserCarVo();
        List<UseCarListVo> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(useCarListDto.getStartPage(), useCarListDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<UseCar> outReports = useCarMapper.selectByExample(example);
        for (UseCar leaving : outReports) {
            UseCarListVo outVo = new UseCarListVo();
            outVo.setId(leaving.getId());
            outVo.setName(leaving.getUserName());
            outVo.setCarNo(leaving.getCarNo());
            outVo.setRemark(leaving.getRemark());
            outVo.setStatus(leaving.getStatus());
            outVo.setStartTime(TimeTool.dateFormat(leaving.getStartTime()));
            outVo.setEndTime(TimeTool.dateFormat(leaving.getEndTime()));
            outVo.setDriverName(leaving.getDriverName());
            outVo.setJoinNames(leaving.getJoinNames());
            voList.add(outVo);
        }
        vo.setTotal(page.getTotal());
        vo.setList(voList);
        return vo;
    }

    /**
     * 确认用车申请
     *
     * @param carConfirmDto
     */
    @Override
    public void carConfirm(CarConfirmDto carConfirmDto) throws Exception {
        UseCar useCar = useCarMapper.selectByPrimaryKey(carConfirmDto.getId());
        if (useCar == null) {
            throw new Exception("数据异常");
        }
        if (useCar.getStatus().equals(0)) {
            useCar.setCarId(carConfirmDto.getCarId());
            useCar.setDriverId(carConfirmDto.getDriverId());
            useCar.setCarNo(carConfirmDto.getCarNo());
            useCar.setDriverName(carConfirmDto.getDriverName());
            useCar.setStatus(1);
            useCarMapper.updateByPrimaryKeySelective(useCar);
        }
    }

    /**
     * 拒绝用车申请
     *
     * @param carRefuseDto
     */
    @Override
    public void carRefuse(CarRefuseDto carRefuseDto) throws Exception {
        UseCar useCar = useCarMapper.selectByPrimaryKey(carRefuseDto.getId());
        if (useCar == null) {
            throw new Exception("数据异常");
        }
        if (useCar.getStatus().equals(0)) {
            useCar.setRefuseReason(carRefuseDto.getRefuseReason());
            useCar.setStatus(2);
            useCarMapper.updateByPrimaryKeySelective(useCar);
        }
        //todo 发送消息模板
    }

    /**
     * PC端我要订车
     *
     * @param pcOrderCarDto
     */
    @Override
//    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public Integer PCOrderCar(PCOrderCarDto pcOrderCarDto) throws Exception {
        UseCarExample example = new UseCarExample();
        System.out.println("用车申请" + JSONObject.toJSONString(pcOrderCarDto));
        example.or().andStartTimeGreaterThanOrEqualTo(new Date(pcOrderCarDto.getStartTime())).andStartTimeLessThan(new Date(pcOrderCarDto.getEndTime())).andStatusEqualTo(StatusEnums.NO.getEcode()).andCarIdEqualTo(pcOrderCarDto.getCarId());
        example.or().andStartTimeLessThanOrEqualTo(new Date(pcOrderCarDto.getStartTime())).andEndTimeGreaterThanOrEqualTo(new Date(pcOrderCarDto.getEndTime())).andStatusEqualTo(StatusEnums.NO.getEcode()).andCarIdEqualTo(pcOrderCarDto.getCarId());
        example.or().andEndTimeLessThanOrEqualTo(new Date(pcOrderCarDto.getStartTime())).andEndTimeGreaterThanOrEqualTo(new Date(pcOrderCarDto.getEndTime())).andStatusEqualTo(StatusEnums.NO.getEcode()).andCarIdEqualTo(pcOrderCarDto.getCarId());
//        example.createCriteria().andStatusEqualTo(StatusEnums.NO.getEcode()).andStartTimeLessThanOrEqualTo(new Date(pcOrderCarDto.getStartTime())).andEndTimeGreaterThanOrEqualTo(new Date(pcOrderCarDto.getEndTime()));
        List<UseCar> useCars = useCarMapper.selectByExample(example);
        if (useCars.size() > 0) {
            throw new Exception("该时段已有预订");
        }
        List<Integer> ids = new ArrayList<>();
        ids.add(pcOrderCarDto.getUserId());

        UseCar useCar = new UseCar();
        useCar.setUserId(pcOrderCarDto.getUserId());
        useCar.setUserName(pcOrderCarDto.getUserName());
        useCar.setStartTime(new Date(pcOrderCarDto.getStartTime()));
        useCar.setEndTime(new Date(pcOrderCarDto.getEndTime()));
        useCar.setRemark(pcOrderCarDto.getRemark());
        useCar.setAddTime(new Date());
        useCar.setCarId(pcOrderCarDto.getCarId());
        useCar.setCarNo(pcOrderCarDto.getCarNo());
        useCar.setStatus(StatusEnums.NO.getEcode());
        useCar.setDriverName(pcOrderCarDto.getDriverName());
        useCar.setDriverId(pcOrderCarDto.getDriverId());
        useCar.setJoinIds(pcOrderCarDto.getJoinIds());
        useCar.setJoinNames(pcOrderCarDto.getJoinNames());
        useCarMapper.insertSelective(useCar);
        //todo 给所有用车随行人员发送消息

        String[] split = pcOrderCarDto.getJoinIds().split(",");
        if (split.length > 0) {
            for (String s : split) {
                ids.add(Integer.valueOf(s));
            }
        }
        Set<String> names = new HashSet<>();
        Set<String> openIds = new HashSet<>();
        for (Integer id : ids) {
            User user = userMapper.selectByPrimaryKey(id);
            names.add(user.getName());
            openIds.add(user.getOpenId());
        }
        Object[] array = names.toArray();
        String splitSetWithComma = StringUtils.join(array, ",");
        //添加司机
        openIds.add(pcOrderCarDto.getDriverId().toString());
        //发送给蔡丽
        User user = userMapper.selectByPrimaryKey(16);
        openIds.add(user.getOpenId());
        for (String openId : openIds) {
            CarNoticeDto outNoticeDto = new CarNoticeDto();
            outNoticeDto.setRemark(useCar.getRemark());
            outNoticeDto.setCarNo(useCar.getCarNo());
            outNoticeDto.setJoinNames(splitSetWithComma);
            outNoticeDto.setOpenId(openId);
            outNoticeDto.setTime(TimeTool.dateFormat(useCar.getStartTime()) + "-" + TimeTool.dateFormat(useCar.getEndTime()));
            weChatService.carNotice(outNoticeDto);

//            User user = userMapper.selectByPrimaryKey(id);
//            Map<String, Template Data> map = new HashMap<>();
//            map.put("car_number12", new TemplateData(pcOrderCarDto.getCarNo()));
//            map.put("time13", new TemplateData(TimeTool.dateFormat(new Date(pcOrderCarDto.getStartTime()))));
//            map.put("time14", new TemplateData(TimeTool.dateFormat(new Date(pcOrderCarDto.getEndTime()))));
//            map.put("thing15", new TemplateData(pcOrderCarDto.getJoinNames()));
//            map.put("thing10", new TemplateData(pcOrderCarDto.getRemark()));
//            weChatService.subscribeMessage(user.getOpenId(), "SpuRwN8qX13U-x13fGooPdwJXWYsvEBwzqcwv6elfBE", null, map);
        }
        return useCar.getId();
    }

    /**
     * 会议日历
     *
     * @param dates
     * @return
     */
    @Override
    public List<MeetingListVo> meetingList(String dates) throws Exception {
        if (StringUtils.isEmpty(dates)) {
            throw new Exception("月份不能为空");
//           dates =  new Date().getTime();
        }
        List<MeetingListVo> listVos = new ArrayList<>();
        Map<String, List<MeetingRoom>> meetingRoomMap = new HashMap<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date date = (Date) formatter.parse(dates);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //第一天的0分0秒
        Date firstDayOfMonth = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        //最后一天的0分0秒
        Date lastDayOfMonth = calendar.getTime();
        Date dayEndTime = TimeTool.getDayEndTime(lastDayOfMonth);//        TimeTool.
        // 获取时间段内所有的会议申请
        MeetingRoomExample example = new MeetingRoomExample();
        example.createCriteria().andBeginTimeGreaterThanOrEqualTo(firstDayOfMonth).andEndTimeLessThanOrEqualTo(dayEndTime).andStatusNotEqualTo(2);
        List<MeetingRoom> meetingRooms = meetingRoomMapper.selectByExample(example);
        for (MeetingRoom meetingRoom : meetingRooms) {
            List<MeetingRoom> value = meetingRoomMap.get(TimeTool.dateFormatNoTime(meetingRoom.getBeginTime()));
            if (value == null) {
                List<MeetingRoom> valueList = new ArrayList<>();
                valueList.add(meetingRoom);
                meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getBeginTime()), valueList);
            } else {
                value.add(meetingRoom);
                meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getBeginTime()), value);
            }
        }
        long now = new Date().getTime();
        for (Map.Entry<String, List<MeetingRoom>> stringListEntry : meetingRoomMap.entrySet()) {
            MeetingListVo vo = new MeetingListVo();
            vo.setDay(stringListEntry.getKey());
            List<MeetingRoom> value = stringListEntry.getValue();
            List<MeetingList> lists = new ArrayList<>();
            List<String> timeList = new ArrayList<>();
            for (MeetingRoom meetingRoom : value) {
                MeetingList meetingList = new MeetingList();
                meetingList.setTpoic(meetingRoom.getTopic());
                meetingList.setJoinNames(meetingRoom.getJoinNames());
                meetingList.setUserName(meetingRoom.getUserName());
                meetingList.setId(meetingRoom.getId());
                meetingList.setStartTime(TimeTool.dateFormatOnlyTime(meetingRoom.getBeginTime()));
                meetingList.setEndTime(TimeTool.dateFormatOnlyTime(meetingRoom.getEndTime()));
                timeList.add(TimeTool.dateFormatOnlyTime(meetingRoom.getBeginTime()) + "-" + TimeTool.dateFormatOnlyTime(meetingRoom.getEndTime()));
                if (now < meetingRoom.getBeginTime().getTime()) {
                    meetingList.setStatus("未开始");
                } else if (now > meetingRoom.getEndTime().getTime()) {
                    meetingList.setStatus("已结束");
                } else {
                    meetingList.setStatus("进行中");
                }
                lists.add(meetingList);
            }
            vo.setList(lists);
            vo.setTimes(timeList);
            if (vo.getList().size() > 4) {
                vo.setFlag(true);
            } else {
                vo.setFlag(false);
            }
            listVos.add(vo);
        }
        return listVos;
    }

    /**
     * 取消会议
     *
     * @param id
     */
    @Override
    public void cancelMeeting(Integer id) throws Exception {
        MeetingRoom meetingRoom = meetingRoomMapper.selectByPrimaryKey(id);
        if (meetingRoom == null) {
            throw new Exception("数据异常");
        }
        Date beginTime = meetingRoom.getBeginTime();
        Date endTime = meetingRoom.getEndTime();
        Date now = new Date();
        if (now.getTime() >= beginTime.getTime()) {
            throw new Exception("该预订无法取消");
        }
        meetingRoom.setStatus(2);
        meetingRoomMapper.updateByPrimaryKeySelective(meetingRoom);
        //todo 通知参会人员
        String[] split = meetingRoom.getJoinIds().split(",");
        for (String s : split) {
            User user = userMapper.selectByPrimaryKey(Integer.valueOf(s));
            JoinMeetingDto joinMeetingDto = new JoinMeetingDto();
            joinMeetingDto.setOpenId(user.getWxOpenId());
            joinMeetingDto.setTopic(meetingRoom.getTopic());
            joinMeetingDto.setTime(TimeTool.dateFormat(meetingRoom.getBeginTime()));
            joinMeetingDto.setJoinNames(user.getName());
            weChatService.cancelMeeting(joinMeetingDto);
//            Map<String, TemplateData> map = new HashMap<>();
//            map.put("thing1", new TemplateData(meetingRoom.getTopic()));
//            map.put("time2", new TemplateData(TimeTool.dateFormat(meetingRoom.getBeginTime())));
//            map.put("thing4", new TemplateData(meetingRoom.getRemark()));
//            weChatService.subscribeMessage(user.getOpenId(), "ZD8BnoXjLaXt2vz1uMgtAjqzz6-x0wxeh_j91XZaAAc", null, map);
        }

    }

    /**
     * 预订会议
     *
     * @param orderMeetingDto
     */
    @Override
    public void orderMeeting(OrderMeetingDto orderMeetingDto) throws Exception {
        MeetingRoomExample example = new MeetingRoomExample();
        example.createCriteria().andStatusEqualTo(StatusEnums.NO.getEcode()).andBeginTimeLessThanOrEqualTo(new Date(orderMeetingDto.getBeginTime())).andEndTimeGreaterThanOrEqualTo(new Date(orderMeetingDto.getEndTime()));
        List<MeetingRoom> meetingRooms = meetingRoomMapper.selectByExample(example);
        if (meetingRooms.size() > 0) {
            throw new Exception("该时段已有预订");
        }
        MeetingRoom meetingRoom = new MeetingRoom();
        meetingRoom.setStatus(1);
        meetingRoom.setUserId(orderMeetingDto.getUid());
        meetingRoom.setUserName(orderMeetingDto.getUserName());
        meetingRoom.setRemark(orderMeetingDto.getRemark());
        meetingRoom.setAddTime(new Date());
        meetingRoom.setBeginTime(new Date(orderMeetingDto.getBeginTime()));
        meetingRoom.setEndTime(new Date(orderMeetingDto.getEndTime()));
        meetingRoom.setTopic(orderMeetingDto.getTopic());
        meetingRoom.setJoinIds(orderMeetingDto.getUids());
        meetingRoom.setJoinNames(orderMeetingDto.getNames());
        meetingRoomMapper.insertSelective(meetingRoom);
        //todo 预订成功后 发送消息
        meetingRoom.setJoinIds(meetingRoom.getJoinIds() + "," + orderMeetingDto.getUid());
        String[] split = meetingRoom.getJoinIds().split(",");
        for (String s : split) {
            User user = userMapper.selectByPrimaryKey(Integer.valueOf(s));
            JoinMeetingDto joinMeetingDto = new JoinMeetingDto();
            joinMeetingDto.setJoinNames(meetingRoom.getJoinNames());
            joinMeetingDto.setTime(TimeTool.dateFormat(meetingRoom.getBeginTime()));
            joinMeetingDto.setTopic(meetingRoom.getTopic());
            joinMeetingDto.setOpenId(user.getOpenId());
            weChatService.joinMeeting(joinMeetingDto);
//            Map<String, TemplateData> map = new HashMap<>();
//            map.put("time1", new TemplateData(TimeTool.dateFormat(meetingRoom.getBeginTime())));
//            map.put("thing3", new TemplateData(meetingRoom.getTopic()));
//            map.put("thing6", new TemplateData(meetingRoom.getJoinNames()));
//            weChatService.subscribeMessage(user.getOpenId(), "BTtoMcaJYn-ah7D83H2BkvIzpG6beoeiGUpfPrR4MgY", null, map);
        }


    }

    /**
     * 员工列表
     *
     * @param userListDto
     * @return
     */
    @Override
    public UserListVo userList(UserListDto userListDto) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(userListDto.getName())) {
            criteria.andNameEqualTo(userListDto.getName());
        }
        if (!StringUtils.isEmpty(userListDto.getDeptName())) {
            criteria.andDeptEqualTo(userListDto.getDeptName());
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode()).andIdNotEqualTo(1);
        UserListVo vo = new UserListVo();
        List<UserList> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(userListDto.getStartPage(), userListDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<User> outReports = userMapper.selectByExample(example);
        for (User leaving : outReports) {
            UserList outVo = new UserList();
            outVo.setId(leaving.getId());
            outVo.setName(leaving.getName());
            outVo.setDept(leaving.getDept());
            outVo.setPhone(leaving.getPhone());
            outVo.setPosition(leaving.getPosition());
            outVo.setAddTime(TimeTool.dateFormat(leaving.getAddTime()));
            voList.add(outVo);
        }
        vo.setTotal(page.getTotal());
        vo.setList(voList);

        return vo;
    }

    /**
     * 添加用户
     *
     * @param addUserDto
     */
    @Override
    public void addUser(AddUserDto addUserDto) throws Exception {
        UserExample example = new UserExample();
        example.createCriteria().andPhoneEqualTo(addUserDto.getPhone()).andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        if (users.size() > 0) {
            throw new Exception("已存在相同的手机号");
        }
        if (addUserDto.getPositionId().equals(3)) {
            UserExample example2 = new UserExample();
            example2.createCriteria().andDeptIdEqualTo(addUserDto.getDeptId()).andStatusEqualTo(StatusEnums.NO.getEcode()).andPositionIdEqualTo(addUserDto.getPositionId());
            List<User> users2 = userMapper.selectByExample(example2);
            if (users2.size() > 0) {
                throw new Exception("部门已存在负责人");
            }
        }
        User user = new User();
        user.setAddTime(new Date());
        user.setName(addUserDto.getName());
        user.setDept(addUserDto.getDeptName());
        user.setPwd("123456");
        user.setStatus(StatusEnums.NO.getEcode());
        user.setPosition(addUserDto.getPosition());
        user.setDeptId(addUserDto.getDeptId());
        user.setPhone(addUserDto.getPhone());
        user.setPositionId(addUserDto.getPositionId());
        userMapper.insertSelective(user);
    }

    /**
     * 编辑用户
     *
     * @param editUserDto
     */
    @Override
    public void editUser(EditUserDto editUserDto) throws Exception {
        if (editUserDto.getPositionId().equals(3)) {
            UserExample example2 = new UserExample();
            example2.createCriteria().andDeptIdEqualTo(editUserDto.getDeptId()).andStatusEqualTo(StatusEnums.NO.getEcode()).andPositionIdEqualTo(editUserDto.getPositionId());
            List<User> users2 = userMapper.selectByExample(example2);
            if (users2.size() > 0) {
                throw new Exception("部门已存在负责人");
            }
        }
        User user = userMapper.selectByPrimaryKey(editUserDto.getId());
        user.setDeptId(editUserDto.getDeptId());
        user.setDept(editUserDto.getDeptName());
        user.setPosition(editUserDto.getPosition());
        user.setPhone(editUserDto.getPhone());
        user.setName(editUserDto.getName());
        user.setPositionId(editUserDto.getPositionId());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 删除用户
     *
     * @param id
     */
    @Override
    public void delUser(Integer id) {
        User user = userMapper.selectByPrimaryKey(id);
        user.setStatus(StatusEnums.YES.getEcode());
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 部门列表
     *
     * @param deptListDto
     * @return
     */
    @Override
    public DeptListVo deptList(DeptListDto deptListDto) {
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(deptListDto.getName())) {
            criteria.andDeptNameEqualTo(deptListDto.getName());
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        DeptListVo vo = new DeptListVo();
        List<DeptList> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(deptListDto.getStartPage(), deptListDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<Dept> outReports = deptMapper.selectByExample(example);
        for (Dept leaving : outReports) {
            DeptList outVo = new DeptList();
            outVo.setId(leaving.getId());
            outVo.setName(leaving.getDeptName());
            outVo.setPhone(leaving.getPhone());
            outVo.setAddTime(TimeTool.dateFormat(leaving.getAddTime()));
            voList.add(outVo);
        }
        vo.setTotal(page.getTotal());
        vo.setList(voList);

        return vo;
    }

    /**
     * 编辑部门
     *
     * @param deptEditDto
     */
    @Override
    public void deptEdit(DeptEditDto deptEditDto) throws Exception {
        Dept dept = deptMapper.selectByPrimaryKey(deptEditDto.getId());
        if (dept == null) {
            throw new Exception("数据异常");
        }
        dept.setPhone(deptEditDto.getPhone());
        deptMapper.updateByPrimaryKeySelective(dept);
    }

    /**
     * 添加部门
     *
     * @param deptAddDto
     */
    @Override
    public void deptAdd(DeptAddDto deptAddDto) throws Exception {
        Dept dept = new Dept();
        dept.setStatus(StatusEnums.NO.getEcode());
        dept.setPhone(deptAddDto.getPhone());
        dept.setDeptName(deptAddDto.getName());
        dept.setAddTime(new Date());
        deptMapper.insertSelective(dept);
    }

    /**
     * 删除部门
     *
     * @param id
     */
    @Override
    public void deptDel(Integer id) throws Exception {
        Dept dept = deptMapper.selectByPrimaryKey(id);
        if (dept == null) {
            throw new Exception("数据异常");
        }
        dept.setStatus(StatusEnums.YES.getEcode());
        deptMapper.updateByPrimaryKeySelective(dept);
    }

    /**
     * 车辆列表
     *
     * @param carListDto
     * @return
     */
    @Override
    public CarListVo carList(CarListDto carListDto) {

        CarExample example = new CarExample();
        CarExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(carListDto.getCarNo())) {
            criteria.andCarNoEqualTo(carListDto.getCarNo());
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        CarListVo vo = new CarListVo();
        List<CarList> voList = new ArrayList<>();
        Page page = PageHelper.startPage(carListDto.getStartPage(), carListDto.getPageSize());
        List<Car> outReports = carMapper.selectByExample(example);
        for (Car leaving : outReports) {
            CarList outVo = new CarList();
            outVo.setId(leaving.getId());
            outVo.setCarNo(leaving.getCarNo());
            outVo.setPhone(leaving.getPhone());
            outVo.setRule(leaving.getRule());
            outVo.setDriverId(leaving.getDriverId());
            outVo.setDriverName(leaving.getDriverName());
            voList.add(outVo);
        }
        vo.setTotal(page.getTotal());
        vo.setList(voList);

        return vo;
    }

    /**
     * 车辆编辑
     *
     * @param carEditDto
     */
    @Override
    public void carEdit(CarEditDto carEditDto) throws Exception {
        Car car = carMapper.selectByPrimaryKey(carEditDto.getId());
        if (car == null) {
            throw new Exception("数据异常");
        }
        car.setCarNo(carEditDto.getCarNo());
        car.setDriverId(carEditDto.getDriverId());
        car.setDriverName(carEditDto.getDriverName());
        car.setPhone(carEditDto.getPhone());
        car.setRule(carEditDto.getRule());
        carMapper.updateByPrimaryKeySelective(car);
    }

    /**
     * 车辆删除
     *
     * @param id
     */
    @Override
    public void carDel(Integer id) throws Exception {
        Car car = carMapper.selectByPrimaryKey(id);
        if (car == null) {
            throw new Exception("数据异常");
        }
        car.setStatus(StatusEnums.YES.getEcode());
        carMapper.updateByPrimaryKeySelective(car);
    }

    /**
     * 用户下拉搜索
     *
     * @param name
     * @param role
     * @return
     */
    @Override
    public List<UserAllListVo> userAllList(String name, String role) {
        List<UserAllListVo> listVos = new ArrayList<>();
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        if (role != null) {
            criteria.andPositionEqualTo(role);
        }
        criteria.andIdNotEqualTo(1);
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        for (User user : users) {
            UserAllListVo vo = new UserAllListVo();
            vo.setName(user.getName());
            vo.setUid(user.getId());
            vo.setPhone(user.getPhone());
            listVos.add(vo);
        }
        return listVos;
    }

    /**
     * 职位列表
     *
     * @return
     */
    @Override
    public List<PositionListVo> positionList() {
        List<PositionListVo> list = new ArrayList<>();
        PositionListVo vo = new PositionListVo();
        vo.setKey(0);
        vo.setPostion("董事长");
        list.add(vo);
        PositionListVo vo1 = new PositionListVo();
        vo1.setKey(1);
        vo1.setPostion("总经理");
        list.add(vo1);
        PositionListVo vo2 = new PositionListVo();
        vo2.setKey(2);
        vo2.setPostion("副总经理");
        list.add(vo2);
        PositionListVo vo3 = new PositionListVo();
        vo3.setKey(3);
        vo3.setPostion("科长");
        list.add(vo3);
        PositionListVo vo4 = new PositionListVo();
        vo4.setKey(4);
        vo4.setPostion("职员");
        list.add(vo4);
        PositionListVo vo5 = new PositionListVo();
        vo5.setKey(5);
        vo5.setPostion("司机");
        list.add(vo5);
        PositionListVo vo6 = new PositionListVo();
        vo6.setKey(4);
        vo6.setPostion("技师");
        list.add(vo6);
        PositionListVo vo7 = new PositionListVo();
        vo7.setKey(4);
        vo7.setPostion("市场助理");
        list.add(vo7);
//        PositionListVo vo8 = new PositionListVo();
//        vo.setKey(5);
//        vo.setPostion("司机");
//        list.add(vo);
//        list.put(0,"董事长");
//        list.put(1,"总经理");
//        list.put(2,"副总经理");
//        list.put(3,"科长");
//        list.put(4,"职员");
//        list.put(5,"司机");
//        list.put(4,"技师");
//        list.put(4,"市场助理");
        return list;
    }

    /**
     * 车辆下拉列表
     *
     * @param carNo
     * @return
     */
    @Override
    public List<CarNoListVo> carNoList(String carNo) {
        List<CarNoListVo> carList = new ArrayList<>();
        CarExample example = new CarExample();
        CarExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(carNo)) {
            criteria.andCarNoEqualTo(carNo);
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        List<Car> cars = carMapper.selectByExample(example);
        for (Car car : cars) {
            CarNoListVo vo = new CarNoListVo();
            vo.setCarNo(car.getCarNo());
            vo.setId(car.getId());
            vo.setDriverId(car.getDriverId());
            vo.setDriverName(car.getDriverName());
            vo.setPhone(car.getPhone());
            carList.add(vo);
        }
        return carList;
    }

    /**
     * 部门下拉列表
     *
     * @param name
     * @return
     */
    @Override
    public List<AllDeptListVo> allDeptList(String name) {
        List<AllDeptListVo> carList = new ArrayList<>();
        DeptExample example = new DeptExample();
        DeptExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(name)) {
            criteria.andDeptNameEqualTo(name);
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        List<Dept> cars = deptMapper.selectByExample(example);
        for (Dept car : cars) {
            AllDeptListVo vo = new AllDeptListVo();
            vo.setId(car.getId());
            vo.setName(car.getDeptName());
            vo.setPhone(car.getPhone());
            carList.add(vo);
        }
        return carList;
    }

    /**
     * 出差添加
     *
     * @param outAddtDto
     */
    @Override
//    @Transactional()
    public void outAdd(OutAddtDto outAddtDto) throws Exception {
        System.out.println("出差添加" + JSON.toJSONString(outAddtDto));
        Integer useCarId = null;
        List<Integer> secondIds = new ArrayList<>();
        PCOrderCarDto pcOrderCarDto = null;
        Boolean carFlag = false;
        List<Integer> ids = new ArrayList<>();
        List<Integer> totalIds = new ArrayList<>();
        List<Integer> sendIds = new ArrayList<>();
        StringBuffer nameStr = new StringBuffer();
        ids.add(outAddtDto.getUid());
        if (!StringUtils.isEmpty(outAddtDto.getJoinIds())) {
            String[] split = outAddtDto.getJoinIds().split(",");
            for (String s : split) {
                ids.add(Integer.valueOf(s));
                sendIds.add(Integer.valueOf(s));
            }
        }
//        ids.add(outAddtDto.getUid());
        for (Integer id : sendIds) {
            String name = userMapper.selectByPrimaryKey(id).getName();
            nameStr.append(name + ",");
        }
        if (nameStr.length() > 0) {
            nameStr.deleteCharAt(nameStr.length() - 1);
        }
        String carNo = "无";
        if (outAddtDto.getCarId() != null) {
            pcOrderCarDto = new PCOrderCarDto();
            pcOrderCarDto.setCarId(outAddtDto.getCarId());
            Car car = carMapper.selectByPrimaryKey(outAddtDto.getCarId());
            carNo = car.getCarNo();
            pcOrderCarDto.setCarNo(car.getCarNo());
            pcOrderCarDto.setDriverId(car.getDriverId());
            pcOrderCarDto.setDriverName(car.getDriverName());
            if (outAddtDto.getJoinIds() == null) {
                pcOrderCarDto.setJoinIds(outAddtDto.getUid().toString());
            } else {
                pcOrderCarDto.setJoinIds(outAddtDto.getJoinIds() + "," + outAddtDto.getUid());
            }
            pcOrderCarDto.setJoinNames(nameStr.toString());
            pcOrderCarDto.setStartTime(outAddtDto.getStartTime());
            pcOrderCarDto.setEndTime(outAddtDto.getEndTime());
            pcOrderCarDto.setUserId(outAddtDto.getUid());
            pcOrderCarDto.setUserName(outAddtDto.getUserName());
            carFlag = Boolean.TRUE;

        }
        //添加主列表
        String firstname = userMapper.selectByPrimaryKey(outAddtDto.getUid()).getName();
        nameStr.append(firstname);
        OutReportExample example = new OutReportExample();
        example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andUserIdEqualTo(outAddtDto.getUid()).andOutTimeStartLessThanOrEqualTo(new Date(outAddtDto.getStartTime())).andOutTimeEndGreaterThanOrEqualTo(new Date(outAddtDto.getEndTime()));
        List<OutReport> outReportsFirst = outReportMapper.selectByExampleWithBLOBs(example);
        if (outReportsFirst.size() > 0) {
            throw new Exception(firstname + "该时段已有预定");
        }

        OutReport first = new OutReport();
        first.setAddTime(new Date());
        first.setAddress(outAddtDto.getAddress());
        first.setOutTimeStart(new Date(outAddtDto.getStartTime()));
        first.setOutTimeEnd(new Date(outAddtDto.getEndTime()));
        first.setUserId(outAddtDto.getUid());
        first.setUserName(firstname);
        first.setRemark(outAddtDto.getRemark());
        first.setPhoto(outAddtDto.getPhoto());
        first.setOrderStatus(1);
        first.setCarId(outAddtDto.getCarId());
        first.setJoinIds(nameStr.toString());
        first.setParentId(0);

        outReportMapper.insertSelective(first);
        Integer parentId = first.getId();
        for (Integer id : sendIds) {
            String name = userMapper.selectByPrimaryKey(id).getName();
            example.clear();
//            OutReportExample example = new OutReportExample();
            example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andUserIdEqualTo(id).andOutTimeStartLessThanOrEqualTo(new Date(outAddtDto.getStartTime())).andOutTimeEndGreaterThanOrEqualTo(new Date(outAddtDto.getEndTime()));
            List<OutReport> outReports = outReportMapper.selectByExampleWithBLOBs(example);
            if (outReports.size() > 0) {
                throw new Exception(name + "该时段已有预定");
            }
            System.out.println("添加随行人员");
            OutReport outReport = new OutReport();
            outReport.setAddTime(new Date());
            outReport.setAddress(outAddtDto.getAddress());
            outReport.setOutTimeStart(new Date(outAddtDto.getStartTime()));
            outReport.setOutTimeEnd(new Date(outAddtDto.getEndTime()));
            outReport.setUserId(id);
            outReport.setUserName(name);
            outReport.setRemark(outAddtDto.getRemark());
            outReport.setPhoto(outAddtDto.getPhoto());
            outReport.setOrderStatus(1);
            outReport.setCarId(outAddtDto.getCarId());
            outReport.setJoinIds(nameStr.toString());
            outReport.setParentId(parentId);
            outReport.setUseCarId(useCarId);
            outReportMapper.insertSelective(outReport);
            secondIds.add(outReport.getId());
        }


        //todo 给所有用户发送差旅行程消息
        HashSet<Integer> sendSet = new HashSet<>(ids);
        ids.clear();
        ids.addAll(sendSet);
        for (Integer id : ids) {
            User user = userMapper.selectByPrimaryKey(id);
            OutNoticeDto outNoticeDto = new OutNoticeDto();
            outNoticeDto.setAddress(outAddtDto.getAddress());
            outNoticeDto.setRemark(outAddtDto.getRemark());
            outNoticeDto.setCarNo(carNo);
            outNoticeDto.setJoins(nameStr.toString());
            outNoticeDto.setOpenId(user.getOpenId());
            outNoticeDto.setTime(TimeTool.dateFormat(new Date(outAddtDto.getStartTime())) + "-" + TimeTool.dateFormat(new Date(outAddtDto.getEndTime())));
            weChatService.outNotice(outNoticeDto);
//            Map<String, TemplateData> map = new HashMap<>();
//            map.put("thing1", new TemplateData(outAddtDto.getAddress()));
//            map.put("time2", new TemplateData(TimeTool.dateFormat(new Date(outAddtDto.getStartTime()))));
//            map.put("time3", new TemplateData(TimeTool.dateFormat(new Date(outAddtDto.getEndTime()))));
//            map.put("car_number4", new TemplateData(carNo));
//            map.put("thing5", new TemplateData(nameStr.toString()));
//            weChatService.subscribeMessage(user.getOpenId(), "MynhfZq9FGKR7nIsXBHyhwP_u1OlVdK20nVUJh78AXc", null, map);
        }
        //更新车辆信息
        if (carFlag) {
            useCarId = this.PCOrderCar(pcOrderCarDto);
//            first.setUseCarId(useCarId);
//            outReportMapper.updateByPrimaryKeySelective(first);
//            for (Integer secondId : secondIds) {
//                OutReport second = new OutReport();
//                second.setId(secondId);
//                second.setUseCarId(useCarId);
//                outReportMapper.updateByPrimaryKeySelective(second);
//            }
        }


    }

    /**
     * 添加车辆
     *
     * @param carAddDto
     */
    @Override
    public void carAdd(CarAddDto carAddDto) {
        Car car = new Car();
        car.setStatus(StatusEnums.NO.getEcode());
        car.setRule(carAddDto.getRule());
        car.setPhone(carAddDto.getPhone());
        car.setDriverId(carAddDto.getDriverId());
        car.setCarNo(carAddDto.getCarNo());
        car.setDriverName(carAddDto.getDriverName());
        carMapper.insertSelective(car);
    }

    /**
     * 新差旅行程
     *
     * @param newOutListDto
     * @return
     */
    @Override
    public List<NewOutListVo> newOutList(NewOutListDto newOutListDto) throws ParseException {
        List<NewOutListVo> vos = new ArrayList<>();
        //todo
        //开始时间
        Date startTime = TimeTool.StringToDateNoTime(newOutListDto.getDate());
        //结束时间
        Date endTime = TimeTool.getNextDay(startTime, 7);
        Date endTime2 = TimeTool.getDayEndTime(startTime);
        endTime = TimeTool.getDayEndTime(endTime);

        OutReportExample example = new OutReportExample();
        System.out.println("结束时间是:======" + TimeTool.dateFormat(endTime));
//        OutReportExample.Criteria criteria = example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andOutTimeStartGreaterThanOrEqualTo(startTime).andOutTimeEndLessThanOrEqualTo(endTime);
        OutReportExample.Criteria criteria = example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andOrModel(TimeTool.dateFormat(startTime), TimeTool.dateFormat(endTime2));
        OutReportDate outReportDate = new OutReportDate();
        if (!StringUtils.isEmpty(newOutListDto.getName())) {
            outReportDate.setUserName(newOutListDto.getName());
        }

        outReportDate.setStartTime(TimeTool.dateFormat(startTime));
        outReportDate.setEndTime(TimeTool.dateFormat(endTime));
        List<OutReport> outReports = outReportMapper.selectByDate(outReportDate);
        Map<String, List<OutReport>> map = new HashMap<>();
        for (OutReport outReport : outReports) {
            List<OutReport> list = map.get(outReport.getUserName());
            if (list != null && list.size() >= 0) {
                list.add(outReport);
                map.put(outReport.getUserName(), list);
            } else {
                list = new ArrayList<>();
                list.add(outReport);
                map.put(outReport.getUserName(), list);
            }
        }
        for (Map.Entry<String, List<OutReport>> entry : map.entrySet()) {
            NewOutListVo vo = new NewOutListVo();
            vo.setName(entry.getKey());
            vo.setList(new HashMap<>());
            Map<String, List<NewOutListInfoVo>> infoMap = new TreeMap<>();
            List<String> daysAll = TimeTool.getinDays(TimeTool.dateFormatNoTime(startTime), TimeTool.dateFormatNoTime(endTime));
            for (String day : daysAll) {
                infoMap.put(day, new ArrayList<>());
            }


//            List<NewOutInfoVo> voList = new ArrayList<>();

            for (OutReport outReport : entry.getValue()) {
                List<String> days = TimeTool.getinDays(TimeTool.dateFormatNoTime(outReport.getOutTimeStart()), TimeTool.dateFormatNoTime(outReport.getOutTimeEnd()));
                for (String day : days) {
                    List<NewOutListInfoVo> listVo = new ArrayList<>();
                    if (infoMap.get(day) != null) {
                        List<NewOutListInfoVo> list = infoMap.get(day);
                        NewOutListInfoVo infoVo = new NewOutListInfoVo();
                        infoVo.setRemark(outReport.getRemark());
                        infoVo.setAddress(outReport.getAddress());
                        infoVo.setTime(TimeTool.dateFormat(outReport.getOutTimeStart()) + "-" + TimeTool.dateFormat(outReport.getOutTimeEnd()));
                        list.add(infoVo);
                        infoMap.put(day, list);
                    } else {
//                        NewOutListInfoVo infoVo = new NewOutListInfoVo();
//                        infoVo.setRemark(outReport.getRemark());
//                        infoVo.setAddress(outReport.getAddress());
//                        infoVo.setTime(TimeTool.dateFormat(outReport.getOutTimeStart())+"-"+TimeTool.dateFormat(outReport.getOutTimeEnd()));
//                        listVo.add(infoVo);
//                        infoMap.put(day, listVo);
                    }

                }
            }
//            Iterator iter = infoMap.entrySet().iterator();
//            while (iter.hasNext()) {
//                Map.Entry entry1 = (Map.Entry) iter.next();
//                Object key = entry1.getKey();
//                Object val = entry1.getValue();
//            }

//            Object[] objects = infoMap.keySet().toArray();
//            Arrays.sort(objects);
            vo.setList(infoMap);
            vos.add(vo);
        }

        return vos;
    }

    /**
     * 查看个人全部行程
     *
     * @param
     * @return
     */
    @Override
    public List<NewOutListVo> userNewOutList(UserNewOutListDto newOutListDto) throws ParseException {
        List<NewOutListVo> vos = new ArrayList<>();
        //todo
        //开始时间
        Date startTime = TimeTool.StringToDateNoTime(newOutListDto.getDate() + "-01");
        //结束时间
        Date endTime = TimeTool.getNextDay(startTime, 31);

        OutReportExample example = new OutReportExample();
        OutReportExample.Criteria criteria = example.createCriteria().andOrderStatusEqualTo(StatusEnums.NO.getEcode()).andOutTimeStartGreaterThanOrEqualTo(startTime).andOutTimeEndLessThanOrEqualTo(endTime);
        if (!StringUtils.isEmpty(newOutListDto.getName())) {
            criteria.andUserNameEqualTo(newOutListDto.getName());
        }
        List<OutReport> outReports = outReportMapper.selectByExample(example);
        Map<String, List<OutReport>> map = new HashMap<>();
        for (OutReport outReport : outReports) {
            List<OutReport> list = map.get(outReport.getUserName());
            if (list != null && list.size() >= 0) {
                list.add(outReport);
                map.put(outReport.getUserName(), list);
            } else {
                list = new ArrayList<>();
                list.add(outReport);
                map.put(outReport.getUserName(), list);
            }
        }
        for (Map.Entry<String, List<OutReport>> entry : map.entrySet()) {
            NewOutListVo vo = new NewOutListVo();
            vo.setName(entry.getKey());
            vo.setList(new HashMap<>());
            Map<String, List<NewOutListInfoVo>> infoMap = new TreeMap<>();
//            List<NewOutInfoVo> voList = new ArrayList<>();

            for (OutReport outReport : entry.getValue()) {
                List<String> days = TimeTool.getinDays(TimeTool.dateFormat(outReport.getOutTimeStart()), TimeTool.dateFormat(outReport.getOutTimeEnd()));
                for (String day : days) {
                    List<NewOutListInfoVo> listVo = new ArrayList<>();
                    if (infoMap.get(day) != null && infoMap.get(day).size() > 0) {
                        List<NewOutListInfoVo> list = infoMap.get(day);
                        NewOutListInfoVo infoVo = new NewOutListInfoVo();
                        infoVo.setRemark(outReport.getRemark());
                        infoVo.setAddress(outReport.getAddress());
                        list.add(infoVo);
                        infoMap.put(day, list);
                    } else {
                        NewOutListInfoVo infoVo = new NewOutListInfoVo();
                        infoVo.setRemark(outReport.getRemark());
                        infoVo.setAddress(outReport.getAddress());
                        listVo.add(infoVo);
                        infoMap.put(day, listVo);
                    }

                }
            }
//            Iterator iter = infoMap.entrySet().iterator();
//            while (iter.hasNext()) {
//                Map.Entry entry1 = (Map.Entry) iter.next();
//                Object key = entry1.getKey();
//                Object val = entry1.getValue();
//            }

//            Object[] objects = infoMap.keySet().toArray();
//            Arrays.sort(objects);
            vo.setList(infoMap);
            vos.add(vo);
        }

        return vos;
//        return null;
    }

    /**
     * 部门查询人员
     *
     * @param deptId
     * @return
     */
    @Override
    public List<UserListByDeptIdVo> userListByDeptId(Integer deptId) {
        List<UserListByDeptIdVo> list = new ArrayList<>();
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        if (deptId != null) {
            criteria.andDeptIdEqualTo(deptId);
        }
        criteria.andStatusEqualTo(StatusEnums.NO.getEcode());
        List<User> users = userMapper.selectByExample(example);
        for (User user : users) {
            UserListByDeptIdVo vo = new UserListByDeptIdVo();
            vo.setUid(user.getId());
            vo.setName(user.getName());
            list.add(vo);
        }
        return list;
    }

    /**
     * 假期类型列表
     *
     * @return
     */
    @Override
    public List<LeaveTypeListVo> leaveTypeList() {
        List<LeaveTypeListVo> leaveTypeListVos = new ArrayList<>();

        for (LeaveingOrderStatusEnums value : LeaveingOrderStatusEnums.values()) {
            LeaveTypeListVo vo = new LeaveTypeListVo();
            vo.setId(value.getEcode());
            vo.setName(value.getEmsg());
            leaveTypeListVos.add(vo);
        }
        return leaveTypeListVos;
    }

    /**
     * 请假统计下载
     *
     * @param loginDto
     * @return
     */
    @Override
    public List<LeaveListDownLoadVo> leaveListDownLoad(LeaveListDto loginDto) {
        LeavingExample example = new LeavingExample();
        LeavingExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(loginDto.getName())) {
            criteria.andUserNameEqualTo(loginDto.getName());
        }
        if (loginDto.getStartTime() != null && loginDto.getEndTime() != null) {
            criteria.andStartTimeGreaterThanOrEqualTo(new Date(loginDto.getStartTime())).andEndTimeLessThanOrEqualTo(new Date(loginDto.getEndTime()));
        }
        if (loginDto.getType() != null) {
            criteria.andTypeEqualTo(loginDto.getType());
        }
        criteria.andStatusEqualTo(1);
        List<LeaveListDownLoadVo> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        List<Leaving> leavings = leavingMapper.selectByExample(example);
        for (Leaving leaving : leavings) {
            LeaveListDownLoadVo leaveVo = new LeaveListDownLoadVo();
            leaveVo.setName(leaving.getUserName());
            leaveVo.setRemark(leaving.getRemark());
            leaveVo.setStatus(OrderTypeEnums.statOf(leaving.getStatus()).getEmsg());
            leaveVo.setType(leaving.getTypeName());
            leaveVo.setRemark(leaving.getRemark());
            leaveVo.setDataStr(TimeTool.dateFormatNoSS(leaving.getStartTime()) + "-" + TimeTool.dateFormatNoSS(leaving.getEndTime()));
            //先获取两天之间所有的days
//            List<String> list = TimeTool.getinDays(TimeTool.dateFormatNoSS(leaving.getStartTime()), TimeTool.dateFormatNoSS(leaving.getEndTime()));
//            for (String s : list) {
//                int ifHoliday = getIfHoliday(s);
//                if (ifHoliday==1||ifHoliday==3){
//
//                }
//            }
            Double datePoor = TimeTool.getDiffByDay(leaving.getEndTime(), leaving.getStartTime());


            double floor = Math.floor(datePoor);
            if (floor + 0.5 < datePoor) {
                datePoor = floor + 1;
            } else if (floor + 0.5 == datePoor + 0.5) {
                datePoor = floor;
            } else {
                datePoor = floor + 0.5;
            }
            //如果在同一天
            if (TimeTool.getDiffDays(leaving.getStartTime(), leaving.getEndTime()) == 0) {
                long nd = 1000 * 24 * 60 * 60;
                long nh = 1000 * 60 * 60;
                long nm = 1000 * 60;
                long diff = leaving.getEndTime().getTime() - leaving.getStartTime().getTime();
                long hour = diff % nd / nh;
                if (hour <= 5) {
                    datePoor = 0.5;

                } else {
                    datePoor = 1.0;
                }
            }
            leaveVo.setDays(datePoor.toString());
            voList.add(leaveVo);
        }
        return voList;
    }

    /**
     * 用车申请下载
     *
     * @param useCarListDto
     * @return
     */
    @Override
    public List<UseCarListDownLoadVo> useCarListDownLoad(UseCarListDto useCarListDto) {
        UseCarExample example = new UseCarExample();
        UseCarExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(useCarListDto.getName())) {
            criteria.andUserNameEqualTo(useCarListDto.getName());
        }
        if (useCarListDto.getStartTime() != null && useCarListDto.getEndTime() != null) {
            criteria.andStartTimeLessThanOrEqualTo(new Date(useCarListDto.getStartTime())).andEndTimeGreaterThanOrEqualTo(new Date(useCarListDto.getEndTime()));
        }
        if (useCarListDto.getStatus() != null) {
            criteria.andStatusEqualTo(useCarListDto.getStatus());
        }
        if (useCarListDto.getCarId() != null) {
            criteria.andCarIdEqualTo(useCarListDto.getCarId());
        }
        List<UseCarListDownLoadVo> voList = new ArrayList<>();
        example.setOrderByClause("add_time desc");
        List<UseCar> outReports = useCarMapper.selectByExample(example);
        for (UseCar leaving : outReports) {
            UseCarListDownLoadVo outVo = new UseCarListDownLoadVo();
            outVo.setName(leaving.getUserName());
            outVo.setCar(leaving.getCarNo());
            outVo.setRemark(leaving.getRemark());
            outVo.setTime(TimeTool.dateFormat(leaving.getStartTime()) + "-" + TimeTool.dateFormat(leaving.getEndTime()));
            outVo.setDriver(leaving.getDriverName());
            outVo.setJoins(leaving.getJoinNames());
            voList.add(outVo);
        }
        return voList;
    }

    /**
     * 通知列表
     *
     * @param newsListDto
     * @return
     */
    @Override
    public NewsListVo newsList(NewsListDto newsListDto) {
        NewsListVo newsListVo = new NewsListVo();
        List<NewsList> list = new ArrayList<>();
        NewsExample example = new NewsExample();
        NewsExample.Criteria criteria = example.createCriteria();
        if (!StringUtils.isEmpty(newsListDto.getTopic())) {
            criteria.andTopicLike(newsListDto.getTopic());
        }
        example.setOrderByClause("add_time desc");
        Page page = PageHelper.startPage(newsListDto.getStartPage(), newsListDto.getPageSize());
        PageHelper.orderBy("add_time desc");
        List<NewsWithBLOBs> newsWithBLOBs = newsMapper.selectByExampleWithBLOBs(example);
        for (NewsWithBLOBs newsWithBLOB : newsWithBLOBs) {
            NewsList newsList = new NewsList();
            newsList.setTopic(newsWithBLOB.getTopic());
            newsList.setContent(newsWithBLOB.getContent());
            newsList.setFile(newsWithBLOB.getFile());
            newsList.setFileNames(newsWithBLOB.getFileNames());
            newsList.setAddTime(TimeTool.dateFormat(newsWithBLOB.getAddTime()));
            newsList.setId(newsWithBLOB.getId());
            list.add(newsList);
        }
        newsListVo.setList(list);
        newsListVo.setTotal(page.getTotal());
        return newsListVo;
    }

    /**
     * 添加通知
     *
     * @param addNews
     */
    @Override
    public void addNews(AddNews addNews) {
        NewsWithBLOBs news = new NewsWithBLOBs();
        news.setAddTime(new Date());
        news.setTopic(addNews.getTopic());
        news.setContent(addNews.getContent());
        news.setFile(addNews.getFile());
        news.setFileNames(addNews.getFileNames());
        newsMapper.insert(news);
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    @Override
    public String upLoadPhoto(MultipartFile file) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
//...其他参数参考类注释

        UploadManager uploadManager = new UploadManager(cfg);
//...生成上传凭证，然后准备上传
        String accessKey = "XXIFDSFml6O1vjrvvggHiKd7V00vuC0yP0SU6Q_4";
        String secretKey = "5SvAdizQq_dvxwV0ERHOaB_xhhp0vu-VtHyMFv5Q";
        String bucket = "baojie58";

//默认不指定key的情况下，以文件内容的hash值作为文件名
//        String key = file.getName();
        String key = file.getOriginalFilename();

        try {
//            byte[] uploadBytes = "hello qiniu cloud".getBytes("utf-8");
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                Response response = uploadManager.put(byteInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "https://cdn.fledchina.com/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (IOException ex) {
            //ignore
        }


        return null;
    }

    /**
     * 获取通知总数
     *
     * @return
     */
    @Override
    public int newsCount() {
        List<NewsWithBLOBs> newsWithBLOBs = newsMapper.selectByExampleWithBLOBs(new NewsExample());
        return newsWithBLOBs.size();
    }

    /**
     * 新用车列表
     *
     * @param dates
     * @return
     */
    @Override
    public List<NewUseCarListVo> newUseCarList(String dates) throws Exception {
        if (StringUtils.isEmpty(dates)) {
            throw new Exception("月份不能为空");
//           dates =  new Date().getTime();
        }
        List<NewUseCarListVo> listVos = new ArrayList<>();
        Map<String, List<UseCar>> meetingRoomMap = new HashMap<>();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM");
        Date date = (Date) formatter.parse(dates);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        //第一天的0分0秒
        Date firstDayOfMonth = calendar.getTime();
        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        //最后一天的0分0秒
        Date lastDayOfMonth = calendar.getTime();
        Date dayEndTime = TimeTool.getDayEndTime(lastDayOfMonth);//        TimeTool.
        // 获取时间段内所有的会议申请
        UseCarExample example = new UseCarExample();
//        example.createCriteria().andBeginTimeGreaterThanOrEqualTo(firstDayOfMonth).andEndTimeLessThanOrEqualTo(dayEndTime).andStatusNotEqualTo(2);
//        example.createCriteria().andStartTimeGreaterThanOrEqualTo(firstDayOfMonth).andEndTimeLessThanOrEqualTo(dayEndTime).andStatusEqualTo(1);
        UseCarExample.Criteria criteria = example.createCriteria().andStatusEqualTo(1);
        criteria.andStartTimeBetween(firstDayOfMonth,dayEndTime);
        example.or().andEndTimeBetween(firstDayOfMonth,dayEndTime).andStatusEqualTo(1);
        List<UseCar> meetingRooms = useCarMapper.selectByExample(example);
        for (UseCar meetingRoom : meetingRooms) {
            List<UseCar> value = meetingRoomMap.get(TimeTool.dateFormatNoTime(meetingRoom.getStartTime()));
            if (value == null) {
                List<UseCar> valueList = new ArrayList<>();
                valueList.add(meetingRoom);
                meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getStartTime()), valueList);
                boolean sameDate = TimeTool.isSameDate(meetingRoom.getStartTime(), meetingRoom.getEndTime());
                if (!sameDate){
                    List<UseCar> useCars = meetingRoomMap.get(TimeTool.dateFormatNoTime(meetingRoom.getEndTime()));
                    if (useCars==null){
                        meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getEndTime()), valueList);
                    }else {
                        useCars.addAll(valueList);
                        meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getEndTime()), useCars);
                    }
//                    meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getEndTime()), valueList);
                }
            } else {
                value.add(meetingRoom);
                meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getStartTime()), value);
                boolean sameDate = TimeTool.isSameDate(meetingRoom.getStartTime(), meetingRoom.getEndTime());
                if (!sameDate){
                    meetingRoomMap.put(TimeTool.dateFormatNoTime(meetingRoom.getEndTime()), value);
                }
            }
        }
        long now = new Date().getTime();
        for (Map.Entry<String, List<UseCar>> stringListEntry : meetingRoomMap.entrySet()) {
            NewUseCarListVo vo = new NewUseCarListVo();
            vo.setDay(stringListEntry.getKey());
            List<UseCar> value = stringListEntry.getValue();
            List<UseCarList> lists = new ArrayList<>();
            List<String> timeList = new ArrayList<>();
            for (UseCar meetingRoom : value) {
                UseCarList meetingList = new UseCarList();
                meetingList.setRemark(meetingRoom.getRemark());
                meetingList.setJoinNames(meetingRoom.getJoinNames());
                meetingList.setUserName(meetingRoom.getUserName());
                meetingList.setId(meetingRoom.getId());
                meetingList.setDriverName(meetingRoom.getDriverName());
                meetingList.setCarNo(meetingRoom.getCarNo());
                meetingList.setStartTime(TimeTool.dateFormatOnlyTime(meetingRoom.getStartTime()));
                meetingList.setEndTime(TimeTool.dateFormatOnlyTime(meetingRoom.getEndTime()));
                if (meetingRoom.getStartTime().getTime() > now) {
                    meetingList.setFlag(true);
                } else {
                    meetingList.setFlag(false);
                }
                timeList.add(TimeTool.dateFormatNoSS(meetingRoom.getStartTime()) + "-" + TimeTool.dateFormatNoSS(meetingRoom.getEndTime()));
                lists.add(meetingList);
            }
            vo.setList(lists);
            vo.setTimes(timeList);
            if (vo.getList().size() > 4) {
                vo.setFlag(true);
            } else {
                vo.setFlag(false);
            }
            listVos.add(vo);
        }
        return listVos;
    }

    /**
     * 用车申请 取消
     *
     * @param id
     */
    @Override
    public void PCOrderCarDel(Integer id) throws Exception {
        UseCar useCar = useCarMapper.selectByPrimaryKey(id);
        if (useCar == null) {
            throw new Exception("数据错误");
        }
        if (useCar.getStartTime().getTime() <= new Date().getTime()) {
            throw new Exception("行程中 无法删除");
        }
        useCar.setStatus(StatusEnums.YES.getEcode());
        useCarMapper.updateByPrimaryKeySelective(useCar);
    }

    /**
     * 用车申请编辑
     *
     * @param pcOrderCarEditDto
     */
    @Override
    public void PCOrderCarEdit(PCOrderCarEditDto pcOrderCarEditDto) throws Exception {
        UseCar useCar = useCarMapper.selectByPrimaryKey(pcOrderCarEditDto.getId());
        if (useCar == null) {
            throw new Exception("数据错误");
        }
        if (useCar.getStartTime().getTime() <= new Date().getTime()) {
            throw new Exception("行程中 无法删除");
        }
        UseCar newUseCar = new UseCar();
        BeanUtils.copyProperties(pcOrderCarEditDto, newUseCar);
        newUseCar.setJoinNames(pcOrderCarEditDto.getJoinNames());
        newUseCar.setJoinIds(pcOrderCarEditDto.getJoinIds());
        useCarMapper.updateByPrimaryKeySelective(newUseCar);
    }

    /**
     * 用车详情
     *
     * @param id
     * @return
     */
    @Override
    public UseCar PCOrderCarInfo(Integer id) throws Exception {
        UseCar useCar = useCarMapper.selectByPrimaryKey(id);
        if (useCar == null) {
            throw new Exception("数据错误");
        }
        return useCar;
    }

    /**
     * 外出取消
     *
     * @param id
     */
    @Override
    public void outDel(Integer id) throws Exception {
        OutReport outReport = outReportMapper.selectByPrimaryKey(id);
        if (outReport.getParentId() != 0) {
            throw new Exception("请联系发起人进行取消操作");
        }
        outReport.setOrderStatus(StatusEnums.YES.getEcode());
        outReportMapper.updateByPrimaryKey(outReport);
        OutReportExample example = new OutReportExample();
        example.createCriteria().andParentIdEqualTo(id);
        List<OutReport> outReports = outReportMapper.selectByExampleWithBLOBs(example);
        for (OutReport report : outReports) {
            report.setOrderStatus(StatusEnums.YES.getEcode());
            outReportMapper.updateByPrimaryKey(report);
        }
        //删除用车
        if (outReport.getUseCarId() != null) {
            UseCar useCar = useCarMapper.selectByPrimaryKey(outReport.getUseCarId());
            if (useCar != null) {
                useCar.setStatus(StatusEnums.YES.getEcode());
                useCarMapper.updateByPrimaryKeySelective(useCar);
            }

        }

    }


}
